#include "hystory.h"

using namespace std;

hystory::hystory()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("history");
}

void hystory::createBD()
{
    if(!db.open())
        cout<<(db.lastError()).text().toStdString();

    query=new QSqlQuery;

    if(db.tables().size()==0){
        cout<<"Table is now created. Congratulation"<<endl<<"Table is empty"<<endl;
        query->exec("create table history (inputSignal int, kontrolGrade int, signalAfterTransmit int, mistake int, outputSignal int)");
    }
}

void hystory::add(int inputSignal, int kontrolGrade, int signalAfterTransmit, int mistake, int outputSignal)
{
    query->prepare("INSERT INTO history (inputSignal, kontrolGrade, signalAfterTransmit, mistake, outputSignal) VALUES (:inputSignal, :kontrolGrade, :signalAfterTransmit, :mistake, :outputSignal)");
    query->bindValue(":inputSignal", inputSignal);
    query->bindValue(":kontrolGrade", kontrolGrade);
    query->bindValue(":signalAfterTransmit", signalAfterTransmit);
    query->bindValue(":mistake", mistake);
    query->bindValue(":outputSignal", outputSignal);
    query->exec();
}

void hystory::clear()
{
    query->exec("delete from history");
}

void hystory::initializeModel()
{
    model=new QSqlTableModel;
    model->setTable("history");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();

    model->setHeaderData(0, Qt::Horizontal, QObject::tr("Input signal"));
    model->setHeaderData(1, Qt::Horizontal, QObject::tr("Kontrol signal"));
    model->setHeaderData(2, Qt::Horizontal, QObject::tr("Signal after transmit"));
    model->setHeaderData(3, Qt::Horizontal, QObject::tr("Mistake"));
    model->setHeaderData(4, Qt::Horizontal, QObject::tr("Output signal"));
}

QTableView* hystory::createView()
{
    QTableView* view = new QTableView;
    view->setModel(model);
    view->setWindowTitle("history");
    view->setColumnWidth(2,130);
    view->resize(550,300);
    return view;
}

hystory::~hystory()
{
    db.close();
    delete model;
    delete query;
}
